import win32gui
import win32con
import ctypes
from ctypes import wintypes
GetCursorPos = ctypes.windll.user32.GetCursorPos
ScreenToClient = ctypes.windll.user32.ScreenToClient
GetWindowRect = ctypes.windll.user32.GetWindowRect

class SetWindow:
    def __init__(self,hwnd):
        win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE,
                               win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
                               | win32con.WS_EX_LAYERED)
        win32gui.SetLayeredWindowAttributes(hwnd, 0x000000, 0, win32con.LWA_COLORKEY)
        win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0,
                              win32con.SWP_NOMOVE | win32con.SWP_NOSIZE)
        self.hwnd=hwnd
        self.dragging = False
        self.offset = (0, 0)

    def start_drag(self):
        rect = win32gui.GetWindowRect(self.hwnd)
        cursor_pos = ctypes.wintypes.POINT()
        GetCursorPos(ctypes.byref(cursor_pos))
        self.offset = (cursor_pos.x - rect[0], cursor_pos.y - rect[1])
        self.dragging = True

    def update_drag(self):
        if not self.dragging:
            return

        cursor_pos = ctypes.wintypes.POINT()
        GetCursorPos(ctypes.byref(cursor_pos))

        # 使用屏幕坐标系计算新位置
        new_x = cursor_pos.x - self.offset[0]
        new_y = cursor_pos.y - self.offset[1]

        # 单次API调用更新位置
        win32gui.SetWindowPos(
            self.hwnd, win32con.HWND_TOPMOST,
            new_x, new_y, 0, 0,
            win32con.SWP_NOSIZE | win32con.SWP_NOACTIVATE
        )


